<template>
  <!-- 客服管理 列表 -->
  <div class="app-container">
    <el-form class="search-form-new" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80">

      <el-form-item label="店铺" prop="tenantId" v-hasPermi="['searchTenantID']">
        <el-select v-model="queryParams.tenantId" placeholder="请选择店铺" clearable filterable size="small">
          <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable />
      </el-form-item>
      <el-form-item label="关联游戏" prop="name">
        <el-select collapse-tags multiple filterable v-model="queryParams.gameIdsArr" placeholder="请选择关联游戏" clearable>
          <el-option v-for="(item,key) in gameList" :key="key" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否显示" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
          <el-option v-for="(dict,key) in isShowOptions" :key="key" :label="dict.name" :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item label="即时通讯" prop="imCustom">
        <el-select v-model="queryParams.imCustom" placeholder="请选择状态" clearable>
          <el-option v-for="(dict,key) in IMstateOptions" :key="key" :label="dict.name" :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button v-hasPermi="['tenant:customerService:add']" type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      </el-form-item>

    </el-form>
    <div class="tip">
      <span style="font-size:18px">使用前请务必认真阅读以下事项：</span>
      <div style="color:#333">
        1、新增客服时可选择<span style="color:red;">是否启用</span>即时通讯功能。<br />
        2、客服启用即时通讯功能后，会每天扣除即时通讯使用费， <span style="color:red;font-size:18px">{{yudou}}</span> 虞豆/客服/天。<br />
        3、首次启用立即扣除<span style="color:red;">当天</span>费用，后续每天<span style="color:red;">5:00</span>扣除当天费用，虞豆不足时系统自动<span style="color:red;">停用</span>客服的即时通讯功能。<br />
        4、当<span style="color:red;">虞豆不足</span>系统停用即时通讯功能时，<span style="color:green;">充值虞豆</span>后次日5:00会<span style="color:red;">自动扣费</span>并<span style="color:green;">开启即时通讯</span>；如需立即启用即时通讯 ，可手动<span style="color:red;">点击刷新按钮</span>扣除当天费用并开启即时通讯。
      </div>
    </div>

    <div class="table_box">
      <el-table stripe v-loading="loading" :data="accountList">
        <el-table-column label="客服名称" prop="name" />
        <el-table-column label="客服类型" prop="type" show-overflow-tooltip>
          <template slot-scope="scope">
            {{getType(scope.row.type)}}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="关联游戏" prop="gameNames" min-width="150"> </el-table-column>
        <!-- <el-table-column label="QQ" prop="qq" /> -->
        <el-table-column label="微信" prop="weixin" />
        <!-- <el-table-column label="手机号" prop="tel" /> -->
        <el-table-column label="图片" prop="qrCode">
          <template slot-scope="scope">
            <img :src="scope.row.qrCode" alt="" style="height:32px;">
          </template>
        </el-table-column>
        <el-table-column label="是否显示" prop="state">
          <template slot-scope="scope">
            <el-tag :type="isShowOptions[scope.row.state].type">{{isShowOptions[scope.row.state].name}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="即时通讯" prop="imCustom">
          <template slot-scope="scope">
            <el-tag :type="IMstateOptions[scope.row.imCustom].type">{{IMstateOptions[scope.row.imCustom].name}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="系统状态" prop="">
          <template slot-scope="scope">
            <div v-if="scope.row.imCustom==2">
              <span v-if="scope.row.imSystem==2">正常</span>
              <span v-else style="color:red">系统停用</span>
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <span style="margin-right:10px" v-if="scope.row.imCustom==2&&scope.row.imSystem==1">
              <el-button v-hasPermi="['tenant:customerService:edit']" type="add" icon="el-icon-edit" @click="refresh(scope.row)">刷新</el-button>
            </span>

            <el-button v-hasPermi="['tenant:customerService:edit']" type="edit" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['tenant:customerService:del']" type="del" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    </div>
    <!-- 添加或修改账号校验对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1150px" append-to-body>
      <el-form class="form-box" ref="form" :model="form" :rules="rules" :inline="true" label-width="100px">
        <el-form-item label="选择用户" prop="customer">
          <virtual-select v-model="form.customer" :list="allUsers" label="nickName" value="userId" :placeholder="'输入关键字用于搜索用户'" :keeps-params="20" :is-concat="false" :concat-symbol="' || '" :is-multiple="false" :disabled="false" :size="'small'" :allow-create="false" @change="userChange" />
        </el-form-item><br />
        <!-- <el-form-item label="客服名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item label="客服类型" prop="typeArr" style="width:100%">
          <el-checkbox-group v-model="form.typeArr" @change="typeChange">
            <el-checkbox v-for="(item,key) in commonMaps.kefuTypeTenantMap" :key="key" :label="key" :value="key">{{item.label}}</el-checkbox>
          </el-checkbox-group>

        </el-form-item><br />
        <el-form-item label="关联游戏" prop="selectGameIds">
          <el-checkbox-group v-model="form.selectGameIds" @change="gameChange">
            <el-checkbox v-for="(item,key) in gameList" :key="key" :label="item.id" :value="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item><br />
        <!-- <el-form-item label="QQ" prop="qq">
          <el-input v-model="form.qq" placeholder="请输入" />
        </el-form-item> -->
        <el-form-item label="微信" prop="weixin">
          <el-input v-model="form.weixin" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="自动回复语" prop="replyContent">
          <span slot="label">
            <el-tooltip content="设置了自动回复后，用户首次联系该客服的时候，系统会自动回复设置的内容。" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            自动回复语
          </span>
          <el-input :rows="3" style="width: 500px;" type="textarea" v-model="form.replyContent" placeholder="请输入" />
        </el-form-item>
        <br />
        <el-form-item label="图片" prop="qrCode">
          <div class="flex" :class="{ 'hiddenupload': qrCodeList.length }">
            <el-input v-model="form.qrCode" v-show="false"></el-input>
            <el-upload class :action="uploadImgUrl" :headers="headers" :file-list="qrCodeList" :show-file-list="true" list-type="picture-card" :limit="1" :on-success="handleAvatarSuccess" :on-remove="handleAvatarRemove" :on-preview="handlePictureCardPreview">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item><br />
        <el-form-item label="是否显示" prop="state">
          <span slot="label">
            <el-tooltip content="表示该客服是否让用户可见" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            是否显示
          </span>
          <el-radio-group v-model="form.state">
            <el-radio v-for="(dict,key) in isShowOptions" :key="key" :label="key">{{ dict.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="即时通讯" prop="imCustom">
          <span slot="label">
            <el-tooltip content="即时通讯功能是收费功能，按天扣除虞豆，开启即时通讯功能后，用户可以在线联系客服，无需添加微信或QQ。" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            即时通讯
          </span>
          <el-radio-group v-model="form.imCustom">
            <el-radio v-for="(dict,key) in IMstateOptions" :key="key" :label="key">{{ dict.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAccount,
  getAccount,
  delAccount,
  addAccount,
  updateAccount,
  exportAccount,
} from "@/api/info/check";
import gameListApi from "@/api/gameConfig/gameList";
import supplyConfigApi from "@/api/system/supplyConfig";
import VirtualSelect from "@/components/VirtualSelect.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "",
  components: {
    VirtualSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 账号校验表格数据
      accountList: [],
      // 弹出层标题
      title: "",
      gameList: [], //所有游戏
      userList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createId: null,
        updateId: null,
        account: null,
        name: null,
        state: null,
        gameIdsArr: [],
      },
      isShowOptions: {
        0: {
          name: "显示",
          type: "success",
        },
        1: {
          name: "隐藏",
          type: "warning",
        },
      },
      IMstateOptions: {
        1: {
          name: "停用",
          type: "danger",
        },
        2: {
          name: "启用",
          type: "success",
        },
      },
      uploadImgUrl: "",
      headers:{},
      qrCodeList: [],
      // 表单参数
      form: {},
      selectGameNames: [],
      allUsers: [], //当前租户下所有用户
      // 表单校验
      rules: {
        customer: [
          { required: true, message: "请选择用户", trigger: "change" },
        ],
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        typeArr: [{ required: true, message: "请选择", trigger: "change" }],
        selectGameIds: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        imCustom: [{ required: true, message: "请选择", trigger: "change" }],
      },
      yudou: "",
    };
  },
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
    getType() {
      return (typeids) => {
        let str = "";
        if (typeids) {
          typeids.split(",").forEach((r) => {
            str += str
              ? "," + this.commonMaps.kefuTypeTenantMap[r].label
              : this.commonMaps.kefuTypeTenantMap[r].label;
          });
        }
        return str;
      };
    },
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
    this.getList();
    this.getGameList();
    this.getAllUserList();
    this.getYudou();
  },
  methods: {
    // 获取客服位虞豆
    getYudou() {
      this.getDicts("points").then((res) => {
        if (res.data && res.data.length) {
          const obj = this.arrayToObject(res.data, "dictLabel");
          this.yudou = Math.abs(obj["imCost"].dictValue);
        }
      });
    },
    // 获取所有用户
    getAllUserList(val) {
      supplyConfigApi.getAllUserList().then((res) => {
        this.allUsers = res.rows;
      });
    },
    /** 查询账号校验列表 */
    getList() {
      this.loading = true;
      listAccount(this.queryParams).then((response) => {
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 游戏列表
    async getGameList() {
      let res = await gameListApi.getGameList();
      res.rows.forEach((r) => {
        r.id = String(r.id);
      });
      this.gameList = res.rows;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 选择客服改变
    userChange(e) {
      this.allUsers.forEach((r) => {
        if (r.userId == e) {
          // this.form.name = r.nickName
          //   const param = {};
          // param.url = url;
          // param.name = name;
          // this.qrCodeList.push({
          //   url:r.ava
          // });
          // this.form.qrCode = res.data.filePath;
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createId: null,
        updateId: null,
        createTime: null,
        updateTime: null,
        account: null,
        name: null,
        state: "0",
        hxname: "",
        customer: "",
        worktype: "1",
        typeArr: [],
        selectGameIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        createId: null,
        updateId: null,
        account: null,
        name: null,
        state: null,
        gameIdsArr: [],
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客服信息";
      this.qrCodeList = [];
      this.form.selectGameIds = [];
      this.selectGameNames = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form.selectGameIds = [];
      this.selectGameNames = [];
      this.qrCodeList = [];
      const id = row.id || this.ids;
      getAccount(id).then((response) => {
        this.form = { ...response.data, typeArr: [], selectGameIds: [] };
        if (this.form.qrCode) {
          this.qrCodeList = [
            {
              url: this.form.qrCode,
              name: "",
            },
          ];
        }
        if (this.form.type) {
          this.form.typeArr = this.form.type.split(",");
        }
        if (this.form.imCustom) {
          this.form.imCustom = String(this.form.imCustom);
        }
        // this.form.type = String(this.form.type)
        if (this.form.gameIds) {
          this.form.selectGameIds = this.form.gameIds.split(",");
          this.selectGameNames = this.form.gameNames.split(",");
        }
        this.open = true;
        this.title = "修改客服信息";
      });
    },
    // 选择类型改变
    typeChange(e) {
      if (e && e.length) {
        this.form.type = e.join(",");
      } else {
        this.form.type = "";
      }
    },
    // 选择游戏改变
    gameChange(e) {
      this.selectGameNames = [];
      this.form.gameIds = e.join(",");
      if (e && e.length) {
        this.gameList.forEach((game) => {
          if (e.includes(game.id)) {
            this.selectGameNames.push(game.name);
          }
        });
      }
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    // 标题图片移除
    handleAvatarRemove(response, file) {
      this.form.qrCode = "";
      this.qrCodeList = [];
    },
    // 标题图片上传成功
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        let url = res.data.filePath;
        let name = res.data.fileName;
        let param = {};
        param.url = url;
        param.name = name;
        this.qrCodeList.push(param);
        this.form.qrCode = res.data.filePath;
      }
    },
    // 刷新系统IM状态
    refresh(row) {
      updateAccount(row).then((response) => {
        this.$modal.msgSuccess("刷新系统状态成功！");
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.selectGameIds.length === 0) {
            return this.$message.error("请选择关联游戏！");
          }
          if (this.form.typeArr.length === 0) {
            return this.$message.error("请选择客服类型！");
          }
          this.form.gameIds = this.form.selectGameIds.join(",");
          this.form.gameNames = this.selectGameNames.join(",");
          this.form.type = this.form.typeArr.join(",");

          if (this.form.id != null) {
            updateAccount(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAccount(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除id为"' + ids + '"的数据项？')
        .then(function () {
          return delAccount(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  
  },
};
</script>
<style scoped>
.tip {
  color: red;
  margin-bottom: 15px;
  white-space: pre-wrap;
}
</style>